package com.yoomiito.app.ui.list

import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.google.android.material.appbar.AppBarLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.Toast
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.gyf.barlibrary.ImmersionBar
import com.yoomiito.app.Constant
import com.yoomiito.app.R
import com.yoomiito.app.adapter.goods.list.NewGiftAdapter
import com.yoomiito.app.adapter.goods.list.NewTaoBaoAdapter
import com.yoomiito.app.adapter.goods.list.sort.ThemeBaoPinGoodsAdapter
import com.yoomiito.app.adapter.goods.list.sort.StarStoreGoodsAdapter
import com.yoomiito.app.adapter.goods.list.sort.ThemeTaoBaoAdapter
import com.yoomiito.app.adapter.goods.list.sort.ThemeYouPinGoodsAdapter
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.BaseList
import com.yoomiito.app.model.gift.GiftGoods
import com.yoomiito.app.model.gift.GiftType
import com.yoomiito.app.model.home.FeaturedGoodsInfo
import com.yoomiito.app.showToast
import com.yoomiito.app.ui.order.sureorder.shopcar.ShopCarActivity
import com.yoomiito.app.utils.*
import com.yoomiito.app.widget.SpacingDecoration
import com.yoomiito.app.widget.state.ContentType
import com.yoomiito.app.widget.state.EmptyType
import com.yoomiito.app.widget.state.StatusManager
import kotlinx.android.synthetic.main.act_goods_sort.*
import kotlinx.android.synthetic.main.fm_rcy.*
import kotlinx.android.synthetic.main.refresh_rcy_layout.*
import kotlin.math.abs

/**
 * 用于特色专区  精选活动
 */
class ThemeGoodsSortListActivity : BaseActivity<ThemeGoodsSortListPresenter>() {

    private var mGoodsType = "" //商品类型
    private var mSort: String = ""//排序
    private var mActId: String = "" //活动Id
    private lateinit var mAdapter: BaseQuickAdapter<GiftGoods, BaseViewHolder>
    private var mCurrentPage: Int = 1

    override fun getLayoutId(): Int = R.layout.act_goods_sort

    override fun newP(): ThemeGoodsSortListPresenter = ThemeGoodsSortListPresenter(App.mAppConfig)

    public override fun initImmersionBar() {
        ImmersionBar.with(this).keyboardEnable(false).init()
    }

    companion object {
        fun start(context: Context, type: String, id: String) {
            val intent = Intent(context, ThemeGoodsSortListActivity::class.java)
//            intent.putExtra(Const.Common.Title, title)
            intent.putExtra(Const.Goods.GOODS_TYPE, type)
            intent.putExtra(Const.Act.ACT_ID,id)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        mGoodsType = intent.getStringExtra(Const.Goods.GOODS_TYPE)
        mActId = intent.getStringExtra(Const.Act.ACT_ID)
        shopCarLl.isEnabled = false
        back.setOnClickListener { finish() }
        initAppbarLayout()
        initTabView()
        initStatusView()
        initRefresh()
        initRcy()
        showLoading()
        requestData()
    }

    private fun initAppbarLayout() {
//        ColorUtils.gradient("#FFFF035B","#FFFF246C")
        toolbarLl.setBackgroundResource(R.color.color_white)
        titleTv.visibility = View.VISIBLE
//        appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, i ->
//            when {
//                i == 0 -> {//展开
//                    toolbarLl.setBackgroundResource(R.color.color_tran)
//                    titleTv.visibility = View.INVISIBLE
//                }
//                abs(i) >= appBarLayout.totalScrollRange -> {//折叠
//                    toolbarLl.background = ColorUtils.gradient("#FFFF035B","#FFFF246C")
//                    titleTv.visibility = View.VISIBLE
//                }
//                else -> {//中间
//                    toolbarLl.setBackgroundResource(R.color.color_tran)
//                    titleTv.visibility = View.INVISIBLE
////                    if (abs(i)>=appBarLayout.totalScrollRange/2){
////                        appBarLayout.setExpanded(false,true)
////                    }else{
////                        appBarLayout.setExpanded(true,true)
////                    }
//                }
//            }
//        })
    }

    private fun initTabView() {
        tabView.setDownName("_des")
                .setUpName("_asc")
                .setPriceFirstName("sale_price")
                .setSaleFirstName("volume")
                .dismissCoupon()
                .setDefault()

//        tabView.setOnChangeListener { sort, _ ->
//            mSort = sort
//            mCurrentPage = 1
//            requestData()
//        }
    }

    private fun initStatusView() {
        mStatusManager = StatusManager.Builder(this)
                .addType(ContentType(R.layout.fm_rcy))
                .addType(EmptyType().setEmptyContent("暂无商品"))
                .build()
        frameLayout.addView(mStatusManager.view())
    }

    private fun initRefresh() {
        fm_refreshLayout.setOnRefreshListener {
            mCurrentPage = 1
            requestData()
        }

        fm_refreshLayout.setOnLoadMoreListener {
            mCurrentPage++
            requestData()
        }
    }

    private fun requestData(){
        p.getList(mActId,mCurrentPage,mSort)
    }

    private fun initRcy() {
        fm_rcy.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
        val sd = SpacingDecoration(DensityUtil.dp2px(10f), DensityUtil.dp2px(10f), false)
        fm_rcy.addItemDecoration(sd)
        fm_rcy.setBackgroundResource(R.color.color_F4F4F4)
        when (mGoodsType) { //'1淘宝商品2礼包商品3爆品商品4优品商品5区代商品',
            "1" -> {
                fm_rcy.removeItemDecoration(sd)
                fm_rcy.layoutManager = androidx.recyclerview.widget.GridLayoutManager(this, 2)
                val space = DensityUtil.dp2px(10f)
                fm_rcy.addItemDecoration(SpacingDecoration(space, space, true))
                mAdapter = ThemeTaoBaoAdapter(null)
            }
            "2" -> mAdapter = NewGiftAdapter(null)
            "3" -> mAdapter = ThemeBaoPinGoodsAdapter(null)//爆品
            "4" -> mAdapter = ThemeYouPinGoodsAdapter(null)//优品
            "5" -> mAdapter = ThemeYouPinGoodsAdapter(null)//区代
        }
        fm_rcy.adapter = mAdapter
        mAdapter?.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
            var info = mAdapter.data[position]
//            RouterUtils.toGoodsDetail(this, info.id.toString(), mGoodsType)
            RouterUtils.toGoodsDetail(this, info.id.toString(), AllCode.getGoodsType(if(info.type==1) 1 else 2,info.product_type,-1))
        }
    }

    fun showData(t: BaseList<GiftGoods>) {
        dismissLoading()
        val data = t.data
        titleTv.text = t.title
        for (it in t.data){
            it.coin = t.coin
        }
        ImageLoader.getInstance().into(this,t.listBanner,actBgAct,R.drawable.default_bg_1)
        if (mCurrentPage == 1) {
            if (data == null || data.size == 0) {
                mStatusManager.showEmpty()
            } else {
                mStatusManager.showContent()
                mAdapter.setNewData(data)
            }
            fm_refreshLayout.finishRefresh(true)
            fm_refreshLayout.setNoMoreData(false)
        } else {
            fm_refreshLayout.finishLoadMore(true)
            if (data == null || data.size == 0) {
                Toast.makeText(context, "没有更多了", Toast.LENGTH_SHORT).show()
                fm_refreshLayout.finishLoadMoreWithNoMoreData()
            } else {
                mAdapter.addData(data)
            }
        }
    }

    fun error(msg:String){
        msg.showToast()
    }

    override fun eventMessage(eventMessage: EventMessage?) {
        super.eventMessage(eventMessage)
        if (Type.EventMsgType.LoginSuccess==eventMessage?.eventType || Type.EventMsgType.LoginOut==eventMessage?.eventType){
            mCurrentPage = 1
            requestData()
        }
    }
}